package com.pactera.asmp.server.job.dispatch.impl.feedback;

import com.pactera.asmp.server.common.constants.DeviceEventType;
import com.pactera.asmp.server.common.constants.DeviceStatus;
import com.pactera.asmp.server.common.constants.TaskEventType;
import com.pactera.asmp.server.common.logprint.utils.CollectionUtils;
import com.pactera.asmp.server.common.websocket.WebSocketServerDevice;
import com.pactera.asmp.server.entity.Subtask;
import com.pactera.asmp.server.entity.TaskDTO;
import com.pactera.asmp.server.entity.TaskDevice;
import com.pactera.asmp.server.job.dispatch.BaseDispatchBus;
import com.pactera.asmp.server.job.dispatch.impl.AsmpTaskDispatchBus;
import com.pactera.asmp.server.job.dispatch.impl.BaseManager;
import com.pactera.asmp.server.job.dispatch.IDeviceEvent;
import com.pactera.asmp.server.job.dispatch.ITaskEvent;
import com.pactera.asmp.server.pojo.DeviceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 反馈管理器
 */
@Slf4j
@Component
public class FeedbackManager extends BaseManager {

    @Autowired
    FeedbackDataRepository repository;

    @Override
    protected BaseDispatchBus initDispatcher() {
        return AsmpTaskDispatchBus.getDispatchBus();
    }

    @Override
    public void deviceEventHandler(IDeviceEvent event) {

    }

    @Override
    public void taskHandler(ITaskEvent event) {

    }

    public void feedbackForDeviceClear(Subtask subtask){
        sendTaskEvent(subtask, TaskEventType.SUBTASK_DEVICE_CLEAR);
    }

    public void feedbackForDeviceFree(Subtask subtask){
        List<TaskDevice> list = repository.getTaskDeviceByTaskIdAndDuid(subtask.getTaskId(), subtask.getDuid());
        if(CollectionUtils.isEmpty(list)){
            log.error("feedbackForDeviceFree not found taskDevice,taskId={}",subtask.getTaskId());
            return ;
        }
        sendTaskDeviceEvent(list.get(0), DeviceEventType.DEVICE_FREE);
    }

    public void feedbackForDeviceOffline(String duid){
        List<TaskDevice> list = repository.getTaskDeviceListByDuid(duid);
        if(CollectionUtils.isEmpty(list)){
            log.info("feedbackForDeviceOffline not found taskDevice,duid={}",duid);
            return;
        }
        sendTaskDeviceEvent(list.get(0), DeviceEventType.DEVICE_OFFLINE);
    }

    public void feedbackForDeviceOfflineMock(String duid){
        List<TaskDevice> list = repository.getTaskDeviceListByDuid(duid);
        if(CollectionUtils.isEmpty(list)){
            log.info("feedbackForDeviceOffline not found taskDevice,duid={}",duid);
            return;
        }
        Session session = getSessionMap().get(duid);
        if(session!=null){
            try {
                session.close();
            }catch (Exception e){

            }
        }
    }

    private Map<String, Session> getSessionMap(){
        HashMap<String, Session> map = new HashMap<>();
        for (String sessionKey : WebSocketServerDevice.id2sessionMap.keySet()) {
            String duid = sessionKey.split("@")[0];
            map.put(duid, WebSocketServerDevice.id2sessionMap.get(sessionKey));
        }
        return map;
    }

    public void feedbackForDeviceOnlineById(String duid){
        DeviceInfo device = repository.getDeviceByDuid(duid);
        if(device == null){
            log.error("not found device, duid={}",duid);
            return;
        }
        device.setStatus(DeviceStatus.FREE.getValue());
        repository.updateStatusByDuid(device);
        //是否有占用设备的task
        List<TaskDevice> list = repository.getTaskDeviceListByDuid(device.getDuid());
        if(CollectionUtils.isEmpty(list)){
            log.info("feedbackForDeviceOnline not found taskDevice,duid={}",device.getDuid());
            return ;
        }
        TaskDevice td = list.get(0);
        // 先查subtask,有没有要cancel,如果有则发cancel事件，没有那么设备空闲
        List<Subtask> stList = repository.getCancelSubtaskByTaskIdAndDuid(duid, td.getTaskId());
        if(CollectionUtils.isEmpty(stList)){
            //没有要取消的task
            sleep(12000L);
            repository.modifyDeviceStatus(td);
            sendTaskDeviceEvent(td, DeviceEventType.DEVICE_FREE);
            return;
        }
        sendTaskEvent(stList.get(0), TaskEventType.SUBTASK_DEVICE_CLEAR);
    }

    public void feedbackForTaskStart(Subtask subtask){
        sendTaskEvent(subtask, TaskEventType.SUBTASK_EXEC);
    }


    public void feedbackForSubtaskComplete(Subtask subtask){
        sendTaskEvent(subtask, TaskEventType.SUBTASK_SUCCESS);
    }

    public void feedbackForTaskComplete(TaskDTO task){
        sendTaskEvent(task, TaskEventType.TASK_COMPLETE);
    }

    public void feedbackForTaskCancel(TaskDTO task){
        sendTaskEvent(task, TaskEventType.TASK_CANCEL);
    }

    public void feedbackForTaskSendEmail(TaskDTO task){
        sendTaskEvent(task, TaskEventType.TASK_SENDEMAIL);
    }

    @Override
    public String getBussinessType() {
        return FeedbackManager.class.getSimpleName();
    }
}
